﻿namespace ClassyBlog.Infrastructure.Specs.Unit
{
    using System.IO;
    using System.Web.Mvc;

    using Machine.Specifications;
    using NSubstitute;

    [Subject(typeof(DefaultViewPageActivator))]
    public class when_creating_a_controller_that_implements_IHasRenderer
    {
        static IDependencyResolver previousDependencyResolver;
        static IRenderer renderer;
        static DefaultViewPageActivator viewPageActivator;
        static DummyView view;

        Establish context = () =>
        {
            previousDependencyResolver = DependencyResolver.Current;

            renderer = Substitute.For<IRenderer>();

            var resolver = Substitute.For<IDependencyResolver>();

            resolver.GetService(typeof(DummyView)).Returns(new DummyView());

            resolver.GetService(typeof(IRenderer)).Returns(renderer);

            DependencyResolver.SetResolver(resolver);

            viewPageActivator = new DefaultViewPageActivator();
        };

        Because of = () =>
            view = (DummyView)viewPageActivator.Create(
            null, typeof(DummyView));

        It should_set_renderer = () =>
            view.Renderer.ShouldBeTheSameAs(renderer);

        Cleanup on_exit = () =>
            DependencyResolver.SetResolver(previousDependencyResolver);

        private sealed class DummyView : IView, IHasRenderer
        {
            public IRenderer Renderer { get; private set; }

            public void SetRenderer(IRenderer renderer)
            {
                Renderer = renderer;
            }

            public void Render(ViewContext viewContext, TextWriter writer)
            {
            }
        }
    }
}